package marble {

	import mx.controls.Alert;
	import mx.core.Application;
	import mx.rpc.AbstractOperation;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.mxml.WebService;

	public class Facade {

		private static var instance:Facade = null;

		private var _locale:Locale;
		private var _webservice:WebService;
		
		private var _currencySymbol:String;
		private var _user_id:int;

		public function Facade(caller:Function = null) {

			if (caller != getInstance) {
				throw new Error("Attempting to instantiate a singleton class.");
			}

			initialize();
		}

		public static function getInstance():Facade {
			if (instance == null) {
				instance = new Facade(arguments.callee);
			}
			return instance;
		}

		public function get locale():Locale {
			return _locale;
		}

		public function get webservice():WebService {
			return _webservice;
		}

		public function get currencySymbol():String {
			return _currencySymbol;
		}

		public function get user_id():int {
			return Application.application.parameters.user_id;
		}

		public function callRemote(name:String, args:Array,
			resultHandler:Function, faultHandler:Function = null):void {
			var op:AbstractOperation = _webservice.getOperation(name);
			op.arguments = args;
			var token:AsyncToken = op.send();
			token.addResponder(new Responder(
				resultHandler,
				(faultHandler != null) ? faultHandler : globalFaultHandler
			));
		}

		private function globalFaultHandler(event:FaultEvent):void {
			Alert.show("" + event.fault, "Error");
		}

		private function initialize():void {

			var params:Object = Application.application.parameters;

			_locale = new Locale(params.language);

			_webservice = new WebService();
			_webservice.showBusyCursor = true;
			_webservice.addEventListener(FaultEvent.FAULT, globalFaultHandler);
			_webservice.loadWSDL("" + params.wsdl);

			callRemote("getCurrecyName", [],
				function (event:ResultEvent):void {
					_currencySymbol = event.result.toString();
				}
			);
		}
	}
}